/* eslint-disable react-hooks/exhaustive-deps */
//获取问卷数据
import { useEffect } from "react";
import { useParams } from "react-router-dom";
import { useRequest } from "ahooks";
import { useDispatch } from "react-redux";
import { getQuestionService } from "../services/question";
import { resetComponents } from "../store/componentsReducer";
import { resetPageInfo } from "../store/pageInfoReducer";

function useLoadQuestionData() {
  const dispatch = useDispatch();
  const { id = "" } = useParams();
  //ajax 数据加载
  const { data, loading, error, run} = useRequest(
    async (id: string) => {
      if (!id) throw new Error("没有问卷id");
      const data = await getQuestionService(id);
      return data;
    },
    { manual: true }
  );
  //根据获取的data 设置redux store
  useEffect(() => {
    if (!data) return;
    const {componentList = [],title='',desc='',js='',css='' ,isPublished=false} = data;
    //获取默认的selectedId
    let selectedId=''
    if(componentList.length>0){
      selectedId=componentList[0].fe_id
    }
    //把componentList 存储到redux store 中
    dispatch(resetComponents({
      componentList, selectedId,
      copiedComponent: null
    }));
    //把pageInfo 存储到redux store 中
    dispatch(resetPageInfo({title,desc,js,css,isPublished}))
  }, [data]);

  //判断ID 变化执行ajax 加载问卷列表
  useEffect(() => {
    run(id);
  }, [id]);
  return { loading, error };
}

export default useLoadQuestionData;
